package cn.com.easy.persistence;

import java.io.IOException;
import java.text.SimpleDateFormat;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.vladmihalcea.hibernate.type.json.JsonStringType;

/**
 * json type适配 jckson <br/>
 * 使用方法
 * 
 * @Entity
 * @Table(name = "pf_json_test")
 * @DynamicInsert
 * @DynamicUpdate
 * @TypeDef(name = "json", typeClass = JsonStringMySqlType.class) public class
 *               JsonTestEntity extends BaseEntity { *
 * @Type(type = "json")
 * @Column(columnDefinition = "json") private Map<Object, Object>
 *                          userProperties;
 * 
 * 
 * @author nibili 2019年12月27日下午7:20:55
 * 
 */
public class JsonTypeJpa extends JsonStringType {

	/** */
	private static final long serialVersionUID = -6102435147727414269L;

	private static ObjectMapper objectMapper = new ObjectMapper();
	static {
		objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
	}

	public JsonTypeJpa() {
		super(objectMapper);
	}

	/**
	 * 将数据库中的未知Object类型，转换为目标 数据类型
	 * 
	 * @param key
	 * @param type
	 * @return
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws JsonProcessingException
	 * @throws IOException
	 * @auth nibili 2020年1月12日 下午1:48:14
	 */
	public static <T> T deserializer(Object key, Class<T> type) throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		return objectMapper.readValue(objectMapper.writeValueAsBytes(key), type);
	}

}
